package com.jhz.speedy.component.control;

import android.app.Activity;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.jhz.speedy.R;
import com.jhz.speedy.common.util.DateUtils;
import com.jhz.speedy.common.util.DialogUtils;
import com.jhz.speedy.common.util.FileUtils;
import com.jhz.speedy.common.util.LogUtils;
import com.jhz.speedy.common.util.NumUtils;
import com.jhz.speedy.common.util.ScreenSizeUtils;
import com.jhz.speedy.component.application.MyApplication;
import com.jhz.speedy.component.receiver.DownEventListeners;
import com.jhz.speedy.component.receiver.DownLoadReceiver;
import com.jhz.speedy.component.service.DownLoadService;
import com.jhz.speedy.logic.apiservice.APIConstance;
import com.jhz.speedy.logic.entity.DownLoadInfo;
import com.jhz.speedy.logic.entity.VersionInfo;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import static android.content.Context.NOTIFICATION_SERVICE;

/**
 * 版本管理器
 * Created by JunHeZ on 2017/7/22.
 */
public class VersionsManage {
    private static final String TAG = VersionsManage.class.getSimpleName();
    private static VersionsManage versionsManage;

    private String fileName = Constants.APK_NAME;   // 文件名
    private String dirName = Constants.FILE_DIR_DOWNLOAD;   // 文件夹
    private float downLoadVersions; // 下载的版本

    private Notification notification;  // 下载通知
    private NotificationManager notificationManager;    // 通知管理器
    private int NOTIFICATION_ID = 201513;   // 通知的id

    private Dialog mDialog; // 进度对话框

    private RemoteViews contentView;    // 通知的视图
    private static final String TAG_AUTO = "auto";  // 自动
    private static final String TAG_COMMON = "common";  // 普通

    private static final int EVENT_ALREADY_NEWEST = 1;  // 已最新
    private static final int EVENT_DOWNLOAD = 2;  // 立即下载
    private static final int EVENT_INSTALL = 3;  // 立即安装

    private VersionsManage() {
        // 下载进度广播监听
        DownLoadReceiver.addDownEventListeners(new DownEventListeners() {
            @Override
            public void onDownEvent(int event, DownLoadInfo downLoadInfo) {
                switch (event) {
                    case DownLoadService.EVENT_DOWNLOAD_START:        // 开始下载初始化发通知
                        initNotification();
                        break;

                    case DownLoadService.EVENT_DOWNLOAD_UPDATE:    // 更新进度
                        updateNotificationProgress(downLoadInfo);   // 更新通知进度
                        break;

                    case DownLoadService.EVENT_DOWNLOAD_FINISH:    // 下载完成
                        cancleNotification();   // 取消通知
                        break;

                    case DownLoadService.EVENT_DOWNLOAD_ERROR:    // 下载出错
                        // 删除文件
                        File file = getApkFile();
                        if (file.exists()) {
                            file.delete();
                        }
                        break;
                }
            }
        });
    }

    public static VersionsManage getInstance() {
        if (versionsManage == null)
            versionsManage = new VersionsManage();

        return versionsManage;
    }

    /**
     * 检测版本
     * @param isAuto 是否自动检测，自动，已最新不显示
     */
    public void checkVersions(final Activity activity, final boolean isAuto) {
        if(mDialog != null && mDialog.isShowing()){
            // 对话框已显示,不再重复处理
            return;
        }

        final String tag;
        if (isAuto) {
            tag = TAG_AUTO;
        } else {
            tag = TAG_COMMON;
        }

        if(! isAuto){
            DialogUtils.getInstance().showLoadDialog(activity, "正在获取版本信息，请稍后！");
        }

        new Thread(){
            @Override
            public void run() {
                final VersionInfo versionInfo = getVersionInfo(); // 版本信息
                if(! isAuto){
                    DialogUtils.getInstance().dismisDialog();
                }
                if(versionInfo != null){
                    // 在当前页面显示升级对话框，如果页面已结束，不处理
                    final Activity currentActivity = MyControl.getActivityManage().getCurrentActivity();
                    if (currentActivity == null || currentActivity.isFinishing()) {
                        return;
                    }

                    currentActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            compareVersions(currentActivity, versionInfo, tag);   // 比较版本
                        }
                    });
                }
            }
        }.start();
    }

    /**
     * 获取最新版本多版本信息
     */
    public VersionInfo getVersionInfo() {
        String path = APIConstance.SERVER_IP_BUSINESS_SHORT + APIConstance.UPDATE_TXT;
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader reader = null;
        try {
            // 创建一个url对象
            URL url = new URL(path);
            // 通過url对象，创建一个HttpURLConnection对象（连接）
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(3000);
            urlConnection.setReadTimeout(3000);

            // 通过HttpURLConnection对象，得到InputStream
            reader = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream()));
            // 使用io流读取文件
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String info = sb.toString();
        VersionInfo versionInfo = null; // 版本信息
        try {
            LogUtils.i(TAG, "update: " + info);
            versionInfo = new VersionInfo();
            versionInfo.setVersion(Float.parseFloat(info.split("&")[1]));
            versionInfo.setDescription(info.split("&")[2]);
            versionInfo.setDownload_url(info.split("&")[3]);
        }catch (Exception e){
            e.printStackTrace();
        }
        return versionInfo;
    }

    /**
     * 比较版本
     * @param versionInfo   服务器最新版本
     * @param isAuto    是否自动检测更新
     */
    private void compareVersions(Activity activity, VersionInfo versionInfo, String isAuto) {
        float currentVersion = Float.parseFloat(MyApplication.getInstance().getPackageInfo().versionName);
        if(versionInfo.getVersion() <= currentVersion){ // 当前版本已最新
            if(TAG_COMMON.equals(isAuto)){  // 手动检测版本的，提示已最新对话框
                showVersionDialog(activity, EVENT_ALREADY_NEWEST, versionInfo, null);
            }

        }else { // 有新版本
            File apkFile = getApkFile();    // apk 文件
            DownLoadInfo downLoadInfo = new DownLoadInfo(apkFile, versionInfo.getDownload_url());

            if (apkFile.exists()) {    // 内存卡 apk 文件存在
                PackageManager packageManager = MyApplication.getInstance().getPackageManager();
                PackageInfo apkFileInfo = packageManager.getPackageArchiveInfo(apkFile.getAbsolutePath(), PackageManager.GET_ACTIVITIES);  // 获取内存卡apk文件的信息

                if (apkFileInfo != null) { // apk文件有效
                    float apkFileVersion = Float.parseFloat(apkFileInfo.versionName);   // 内存卡的安装包版本
                    if (apkFileVersion >= versionInfo.getVersion()) {    // 此安装包为最新，直接装
                        LogUtils.i(TAG, "已下载过最新版本 currentVersion = ");
                        // 立即安装对话框
                        showVersionDialog(activity, EVENT_INSTALL, versionInfo, downLoadInfo);
                        return;
                    }
                }
                apkFile.delete(); // 无效，或者旧版本，删除重新下
            }

            // 立即下载
            downLoadVersions = versionInfo.getVersion();
            Log.d(TAG, "下载apk url = " + versionInfo.getDownload_url());
            showVersionDialog(activity, EVENT_DOWNLOAD, versionInfo, downLoadInfo);
        }
    }

    /**
     * @return 安装包文件
     */
    private File getApkFile() {
        File fileDir = FileUtils.getOrCreateAppDir(dirName);    // 文件夹
        File file = new File(fileDir, fileName);    // apk 文件
        return file;
    }

    private void dismisDialog() {
        if (mDialog != null && mDialog.isShowing())
            mDialog.dismiss();
    }

    /**
     * 版本升级对话框
     */
    private void showVersionDialog(final Activity activity, final int eventDialog, final VersionInfo versionInfo, final DownLoadInfo downLoadInfo){
        dismisDialog();

        mDialog = new Dialog(activity, R.style.dialog_transparent_style);
        mDialog.setContentView(R.layout.dialog_version);
        mDialog.getWindow().getAttributes().width = (int) (ScreenSizeUtils.getScreenWidth() * 0.85f);
        mDialog.setCancelable(false);

        TextView tvTitle = mDialog.findViewById(R.id.tvTitle);  // 抬头
        TextView tvOldVer = mDialog.findViewById(R.id.tvOldVer);    // 旧版本
        TextView tvNewVer = mDialog.findViewById(R.id.tvNewVer);    // 新版本
        TextView tvDate = mDialog.findViewById(R.id.tvDate);    // 日期

        final RelativeLayout layoutProgress = mDialog.findViewById(R.id.layoutProgress);  // 进度布局
        final TextView tvProgress = mDialog.findViewById(R.id.tvProgress);      // 进度
        final ProgressBar progressBar = mDialog.findViewById(R.id.progressBar); // 进度条

        RelativeLayout layoutCancel = mDialog.findViewById(R.id.layoutCancel);  // 取消
        final Button btnOK = mDialog.findViewById(R.id.btnOK);    // 确定

        layoutProgress.setVisibility(View.GONE);   // 隐藏进度布局
        tvOldVer.setText(MyApplication.getInstance().getPackageInfo().versionName);
        tvNewVer.setText(versionInfo.getVersion() + "");
        tvDate.setText(DateUtils.getCurrentDate(DateUtils.PATTERN_DATE));

        switch (eventDialog){
            case EVENT_ALREADY_NEWEST:  // 已最新
                tvTitle.setText("当前版本已最新");
                layoutCancel.setVisibility(View.GONE);
                btnOK.setText("确定");
                break;
            case EVENT_DOWNLOAD:    // 立即下载
                tvTitle.setText("发现新版本");
                layoutCancel.setVisibility(View.VISIBLE);
                btnOK.setText("立即下载");
                break;
            case EVENT_INSTALL: // 立即安装
                tvTitle.setText("发现新版本");
                layoutCancel.setVisibility(View.VISIBLE);
                btnOK.setText("立即安装");
                break;
        }


        btnOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (eventDialog){
                    case EVENT_ALREADY_NEWEST:  // 已最新
                        dismisDialog();
                        break;
                    case EVENT_DOWNLOAD:    // 立即下载
                        layoutProgress.setVisibility(View.VISIBLE);    // 显示进度布局
                        btnOK.setVisibility(View.GONE); // 隐藏确定按钮

                        Intent intent = new Intent(activity,DownLoadService.class);
                        intent.putExtra(DownLoadService.DOWNLOAD_INFO, downLoadInfo);
                        activity.startService(intent);  // 启动下载服务
                        break;

                    case EVENT_INSTALL: // 立即安装
                        FileUtils.installApkFile(downLoadInfo.file);
                        break;
                }
            }
        });

        layoutCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismisDialog();
            }
        });

        final DownEventListeners downEventListeners = new DownEventListeners() {
            @Override
            public void onDownEvent(int event, DownLoadInfo downLoadInfo) {
                if(mDialog == null || !mDialog.isShowing()){    // 对话框已结束，不再处理
                    return;
                }

                switch (event) {
                    case DownLoadService.EVENT_DOWNLOAD_START:        // 开始下载初始化发通知
                        break;

                    case DownLoadService.EVENT_DOWNLOAD_UPDATE:    // 更新进度
                        double progress = NumUtils.getRate(downLoadInfo.downLength, downLoadInfo.totalLength);
                        tvProgress.setText(NumUtils.FormetDoubleString(progress) + "%");
                        progressBar.setProgress((int) progress);
                        break;

                    case DownLoadService.EVENT_DOWNLOAD_FINISH:    // 下载完成
                        tvProgress.setText(100 + "%");
                        progressBar.setProgress(100);
                        FileUtils.installApkFile(downLoadInfo.file);
                        dismisDialog();
                        break;

                    case DownLoadService.EVENT_DOWNLOAD_ERROR:    // 下载出错
                        dismisDialog();
                        break;
                }
            }
        };

        DownLoadReceiver.addDownEventListeners(downEventListeners);

        mDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                DownLoadReceiver.removeDownEventListeners(downEventListeners);
            }
        });
        mDialog.show();
    }

    /**
     * 取消通知
     */
    private void cancleNotification(){
        if (notificationManager != null) {
            notificationManager.cancel(NOTIFICATION_ID);
        }
    }

    /**
     * 更新通知的进度
     */
    private void updateNotificationProgress(DownLoadInfo downLoadInfo) {
        // 更新通知栏
        contentView.setProgressBar(R.id.progressBar, (int) downLoadInfo.totalLength, (int) downLoadInfo.downLength, false);

        contentView.setTextViewText(
                R.id.tvProgress,
                NumUtils.FormetDoubleString(NumUtils.getRate(downLoadInfo.downLength, downLoadInfo.totalLength)) + "%");

        notification.contentView = contentView;
        notificationManager.notify(NOTIFICATION_ID, notification);
    }

    /**
     * 初始化通知栏，并显示，定时刷新
     */
    private void initNotification() {
        // 新建通知
        notification = new Notification();
        notification.icon = R.mipmap.ic_launcher;
        notification.tickerText = "";
        notification.flags = Notification.FLAG_AUTO_CANCEL; // 自动取消

        // 通知布局
        contentView = new RemoteViews(
                MyApplication.getInstance().getPackageName(),
                R.layout.layout_version_update_notification);

        // 初始化通知view
        contentView.setImageViewResource(R.id.ivIcon, R.mipmap.ic_launcher);
        contentView.setTextViewText(R.id.tvVersionName, MyApplication.getInstance().getResources().getString(R.string.app_name) + "更新: " + downLoadVersions);
        contentView.setProgressBar(R.id.progressBar, 0, 0, false);
        contentView.setTextViewText(R.id.tvProgress, "0%");

        // 通知隐式意图
        Intent notificationIntent = new Intent();
        PendingIntent contentIntent = PendingIntent.getActivity(
                MyApplication.getInstance(), NOTIFICATION_ID,
                notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        notification.contentView = contentView;
        notification.contentIntent = contentIntent;

        notificationManager = (NotificationManager) MyApplication.getInstance().getSystemService(NOTIFICATION_SERVICE);

        notificationManager.notify(NOTIFICATION_ID, notification);
    }



}
